
export async function getClockTimeList() {
  // 通过云函数调用获取用户 _openId
  return getApp().getOpenId().then(async openid => {
    // 根据 _openId 数据，查询并展示待办列表
    return byDB('query', { _openid: openid })
  })
}

async function byDB(type, params = {}) {
  const { _id, ...rest } = params
  const db_table_name = getApp().globalData.collectionClockTime
  const db = await getApp().database()
  if (type === 'add') {
    return db.collection(db_table_name).add({
      data: {
        ...rest
      }
    })
  }

  if (type === 'update') {
    return db.collection(db_table_name).where({
      _id: _id
    }).update({
      data: {
        ...rest
      }
    })
  }

  if (type === 'query') {
    return db.collection(db_table_name).where({
      ...rest
    }).get().then(res => {
      return res.data || []
    })
  }
}

export function updateClockTime({ clock_time, clock_type, current_date, prev_data }) {
  if (clock_type === 'am') {
    const new_am_time = new Date(current_date + " " + clock_time)
    const am_end_time = new Date(current_date + " " + "08:20")
    const am_over_time = (am_end_time - new_am_time) / 1000 / 60
    if (prev_data) { // 编辑
      console.log('存在pm_over_time的话需要对total进行处理', prev_data?.pm_over_time)
      return byDB('update', {
        am_over_time,
        am_time: clock_time,
        date: current_date,
        total_over_time: am_over_time,
        _id: prev_data._id
      })
    } else { // 新增
      return byDB('add', {
        am_over_time,
        am_time: clock_time,
        date: current_date,
        total_over_time: am_over_time
      })
    }
  }
  if (clock_type === 'pm') {
    const new_pm_time = new Date(current_date + " " + clock_time)
    const pm_start_time = new Date(current_date + " " + "17:20")
    const pm_over_time = (new_pm_time - pm_start_time) / 1000 / 60
    if (prev_data) {
      console.log('存在pm_over_time的话需要对total进行处理', prev_data)
      const { _id, am_over_time = 0 } = prev_data
      return byDB('update', {
        pm_over_time,
        pm_time: clock_time,
        date: current_date,
        total_over_time: am_over_time + pm_over_time,
        _id: _id
      })
    } else {
      return byDB('add', {
        pm_over_time,
        pm_time: clock_time,
        date: current_date,
        total_over_time: pm_over_time
      })
    }

  }
}